<template>
  <Drawer v-model:show="modalShow" @close="clearFridgeSettingModal">
    <template #header>
      <view class="drawer-title-box">
        <text class="drawer-title">{{ currentGroup?.name }}</text>
        <text class="grawer-title-unit" v-if="showGroupUnit && currentGroup?.unit">({{ currentGroup?.unit }})</text>
        <view
          class="grawer-title-unit"
          v-if="currentGroup?.key === REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE"
          @click="openModal"
          ><image class="setting-icon" mode="aspectFit" :src="'/pages/appliance/static/ic_question_icon.png'"></image
        ></view>
      </view>
    </template>
    <!-- <view :class="currentGroup?.key === 'ModeChoose' ? 'display-around bgGrey bold-font' : ''"> -->
    <view
      :class="{
        'display-around': currentGroup?.key === 'ModeChoose',
        bgGrey: currentGroup?.key === 'ModeChoose',
        ' bold-font': currentGroup?.key === 'ModeChoose',
        'mode-box': newMenuSettings.length > 3,
        'present-box': currentGroup?.key === SETTING_PRESET,
      }"
    >
      <!-- 功能title -->
      <view class="function-title" v-if="currentGroup?.key === SETTING_PRESET">运行模式</view>

      <view
        class="setting-con"
        :class="{
          'mode-con': currentGroup?.key === 'ModeChoose',
          'present-con': currentGroup?.key === SETTING_PRESET,
        }"
        v-for="(setting, settingIndex) in newMenuSettings"
        :key="settingIndex"
      >
        <!--变温室设置-->
        <block v-if="setting.type === 'Flex'">
          <!-- 预设模式 -->
          <view class="setting-box">
            <view class="setting-switch display-between">
              <view class="setting-name">
                <text class="name-text">预设模式</text>
                <image
                  class="question-icon"
                  mode="aspectFit"
                  :src="'/pages/appliance/static/ic_question_icon.png'"
                  @click="showNotifyTip('presetMode')"
                ></image>
              </view>
              <!-- <switch
                v-if="setting.constraints?.extrovalue"
                color="#408DF2"
                :checked="setting.value !== FLEX_MODE_CUSTOM"
                @change="toggleChangeFlex(setting)"
              /> -->
            </view>

            <view class="setting-in pad-top">
              <view class="flex-grid">
                <view
                  class="grid-cont"
                  v-for="(option, index) in control.store.isVirtualAppliance ? flexDemoMode : flexModes"
                  :key="index"
                  :class="{
                    active:
                      flexModeIndex == -100
                        ? setting.value === setting.constraints?.allowedvalues?.[index]
                        : option.value == `${flexModeIndex}`,
                  }"
                  @click="flexOptionChange(setting.key, option as any)"
                >
                  <text class="grid-name">{{ brand === 'SIEMENS' ? option.SIEMENS_name : option.BOSCH_name }}</text>
                  <!-- <text>{{ option.value }}℃</text> -->
                </view>
              </view>
            </view>
          </view>
          <!-- 自定义类型 -->
          <view class="setting-box" v-if="localMode">
            <view class="setting-switch display-between">
              <view class="setting-name">
                <text class="name-text">{{ setting.constraints?.extrovalue?.displayvalue }}</text>
                <image
                  v-if="localMode?.modelName"
                  class="question-icon"
                  mode="aspectFit"
                  :src="'/pages/appliance/static/ic_question_icon.png'"
                  @click="showNotifyTip('selfSetMode')"
                ></image>
              </view>
              <!-- <switch
                color="#408DF2"
                :checked="setting.value === FLEX_MODE_CUSTOM"
                @change="toggleChangeFlex(setting)"
              /> -->
            </view>
            <view class="setting-in pad-top" v-if="localMode">
              <view
                :class="{
                  active:
                    flexModeIndex == -100
                      ? setting.value === setting.constraints?.extrovalue?.allowedvalue
                      : localMode?.temperature == flexModeIndex,
                  inactive: setting.value !== FLEX_MODE_CUSTOM,
                }"
                @click="setNewLocalMode(localMode.temperature)"
              >
                <text class="localmode-title">{{ localMode?.modelName }}</text>
                <text>{{ localMode?.temperature }}℃</text>
              </view>
            </view>
          </view>
        </block>
        <!--活氧净设置-->
        <block v-else-if="setting.type === 'SmartHygiene'">
          <view class="setting-box">
            <view class="setting-name">
              <text class="name-text">运行模式</text>
            </view>
            <view class="setting-in display-around pad-top">
              <view
                class="mode-font"
                :class="{
                  active: smartHygieneClose,
                }"
                @click="setSmartHygieneEnabled(false, setting.key, 'Appliance.Settings.SmartHygiene.Close')"
                >{{ $t('Appliance.Settings.SmartHygiene.Close') }}</view
              >
              <view
                class="mode-font"
                :class="{
                  active: smartHygieneAuto,
                }"
                @click="setSmartHygieneEnabled(true, setting.key, 'Appliance.Settings.SmartHygiene.Auto')"
                >{{ $t('Appliance.Settings.SmartHygiene.Auto') }}</view
              >
              <view
                class="mode-font"
                :class="{
                  active: smartHygieneStrongSterilization,
                }"
                @click="setSmartHygieneManual(setting.key, 'Appliance.Settings.SmartHygiene.StrongSterilization')"
                >{{ $t('Appliance.Settings.SmartHygiene.StrongSterilization') }}</view
              >
            </view>
          </view>

          <view class="mode-des">{{
            smartHygienMode === SMART_HYGIENE_MODE_MANUAL || smartHygieneLiteMode === SMART_HYGIENE_MODE_MANUAL
              ? '此模式可随时终止，或在连续运行24小时后自动退出'
              : ''
          }}</view>
          <!-- 勿扰模式 -->
          <view v-if="!control.store.isVirtualAppliance">
            <view
              class="not-disturb-mode"
              v-if="isNotDisturbMode"
              :class="{
                inactive:
                  smartHygienMode === SMART_HYGIENE_MODE_CLOSE || smartHygieneLiteMode === SMART_HYGIENE_MODE_CLOSE,
              }"
            >
              <view class="not-disturb-title" @click="setNodisturb">
                <image
                  v-if="isSmartHygieneNodisturb"
                  class="select-img"
                  mode="aspectFit"
                  :src="'/static/ic_selected_radio.png'"
                ></image>
                <image v-else class="select-img" mode="aspectFit" :src="'/static/ic_unselected_radio.png'"></image>
                <text>勿扰模式</text>
              </view>
              <view class="not-disturb-cont"> 启动勿扰模式后，你将不会收到关于冰箱内空气质量的消息推送和警报。 </view>
            </view>
            <view v-else style="height: 124rpx"></view>
          </view>
          <!-- 虚拟家电勿扰模式 -->
          <view v-else>
            <view class="not-disturb-mode" v-if="!smartHygieneClose">
              <view class="not-disturb-title" @click="setNodisturb">
                <image
                  v-if="!swithchValueTypes"
                  class="select-img"
                  mode="aspectFit"
                  :src="'/static/ic_selected_radio.png'"
                ></image>
                <image v-else class="select-img" mode="aspectFit" :src="'/static/ic_unselected_radio.png'"></image>

                <text>勿扰模式</text>
              </view>
              <view class="not-disturb-cont"> 启动勿扰模式后，你将不会收到关于冰箱内空气质量的消息推送和警报。 </view>
            </view>
            <view v-else style="height: 124rpx"></view>
          </view>
        </block>

        <!--模式选择-->
        <block v-else-if="setting.type === 'Mode'">
          <view
            class="setting-mode"
            :class="{ active: setting.value }"
            @click="modeChange(setting)"
            v-if="!control.store.isVirtualAppliance"
          >
            <text style="font-weight: 600"> {{ setting.name }}</text>
          </view>
          <view
            v-else
            class="setting-mode"
            :class="{ active: modeHeightLight == settingIndex }"
            @click="modeChange(setting, settingIndex)"
          >
            <text style="font-weight: 600"> {{ setting.name }}</text>
          </view>
        </block>
        <!-- Specialty Zone -->
        <block v-else-if="setting.type === 'present'">
          <view
            v-if="setting.statusValue"
            class="present-mode"
            @click="choosePresentMode(setting)"
            :class="{
              active: setting.activePreset,
            }"
          >
            {{ setting.displayvalue }}
          </view>
        </block>
        <!--其它option设置-->
        <!--bool值设置-->
        <block v-else-if="setting.type === 'Boolean' || setting.type === 'Radio'">
          <view class="setting-box special-bottom">
            <view class="setting-in">
              <view class="setting-name bool-name">
                <text class="name-text" style="opacity: 1">{{ setting.name }}</text>
              </view>
              <switch color="#408DF2" :checked="setting.value" @change="toggleChange(setting)" />
            </view>
          </view>
        </block>

        <!--滚动值设置-->
        <block v-else-if="setting.type === 'Picker'">
          <view class="setting-box">
            <view class="setting-name">
              <view class="name">
                <text class="name-text">{{ setting.name }}</text>
                <text class="setting-unit" v-if="setting.unit">({{ setting.unit }})</text>
              </view>
            </view>
            <view class="setting-in pad-top jia-jian-box">
              <view
                class="decrease"
                :class="{
                  inactive:
                    (currentGroup?.key === FLEX_KEY
                      ? flexModeIndex === setting.constraints?.min
                      : setting.constraints?.min === setting.value) || isDisabledTemp(setting),
                }"
                @click="decrease(setting)"
              >
                <image class="mark-icon" :src="'/pages/appliance/static/ic_decrease_icon.png'"></image>
              </view>

              <view
                v-if="!control.store.isVirtualAppliance"
                class="num"
                :class="{
                  inactive:
                    currentGroup?.key === FLEX_KEY
                      ? false
                      : setting.constraints?.min === setting.constraints?.max || isDisabledTemp(setting),
                  'is-setpoint-temperature': currentGroup?.key === REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE,
                }"
                >{{ setting.value }}</view
              >
              <view
                v-else
                class="num"
                :class="{
                  inactive:
                    currentGroup?.key === FLEX_KEY
                      ? false
                      : setting.constraints?.min === setting.constraints?.max || isDisabledTemp(setting),
                  'is-setpoint-temperature': currentGroup?.key === REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE,
                }"
                >{{ currentGroup?.key === FLEX_KEY ? flexModeIndex : setting.value }}</view
              >
              <view
                class="increase"
                :class="{
                  inactive:
                    (currentGroup?.key === FLEX_KEY
                      ? flexModeIndex === setting.constraints?.max
                      : setting.constraints?.max === setting.value) || isDisabledTemp(setting),
                }"
                @click="increase(setting)"
              >
                <image class="mark-icon" :src="'/pages/appliance/static/ic_add_icon.png'"></image>
              </view>
            </view>
          </view>
        </block>

        <!--枚举值设置-->
        <block v-else-if="setting.type === 'Enum'">
          <view class="setting-box">
            <view class="setting-name"
              ><text class="name-text">{{ setting.name }}</text></view
            >
            <view class="setting-in pad-top">
              <view class="display-around widthFull">
                <view
                  class="grid-cont"
                  v-for="(option, index) in setting.constraints?.displayvalues || []"
                  :key="index"
                  :class="{ active: setting.value === setting.constraints?.allowedvalues?.[index] }"
                  @click="optionChange(setting, index)"
                  >{{ option }}</view
                >
              </view>
            </view>
          </view>
        </block>
      </view>
    </view>
  </Drawer>
  <!-- 预设模式说明 -->
  <Modal :visible="showTip2" title="预设模式说明" ok-text="知道了" @ok="showTip2 = false">
    <view
      class="modal-list"
      v-for="(item, index) in control.store.isVirtualAppliance ? flexDemoMode : flexModes"
      :key="index"
    >
      <text class="list-title">{{ brand == 'SIEMENS' ? item.SIEMENS_name : item.BOSCH_name }}：</text>
      <text class="list-cont">{{ brand == 'SIEMENS' ? item.siemens_des : item.bosch_des }}</text>
    </view>
  </Modal>
  <!-- 自定义模式说明 -->
  <Modal :visible="showTip3" title="自定义模式说明" ok-text="知道了" @ok="showTip3 = false">
    <view class="modal-list">
      <text class="list-title">{{ localMode?.modelName }}：</text>
      <text class="list-cont">{{ localMode?.description }}</text>
    </view>
  </Modal>
  <!-- 零度维他弹窗提示 -->
  <Modal
    v-model:visible="isShowTips"
    :title="$t('FridgeFreezer.FlexCompartment.SetpointTemperature.title.Text')"
    :ok-text="$t('FridgeFreezer.FlexCompartment.SetpointTemperature.Confirm.Text')"
    @ok="isShowTips = false"
  >
    <view class="SetpointTemperature-tips">
      {{ $t('FridgeFreezer.FlexCompartment.SetpointTemperature.tips.Text') }}
    </view>
  </Modal>
</template>

<script setup lang="ts">
import Modal from '@/common/modal.vue'
import Drawer from '@/common/drawer.vue'

import { setSetting, type ApplianceSetting, setCommand, getSetting } from '@/api/appliance'
import {
  FLEX_KEY,
  FLEX_MODE_CUSTOM,
  FLEX_MODE_KEY,
  SMART_HYGIENE_BOOST,
  SMART_HYGIENE_CLOSED,
  SMART_HYGIENE_ENABLED,
  SMART_HYGIENE_NO_DISTURB,
  SMART_HYGIENE_MODE_CLOSE,
  SMART_HYGIENE_MODE_AUTO,
  SMART_HYGIENE_MODE_MANUAL,
  REFRIGERATION_OFF_MODE,
  REFRIGERATION_VACATION_MODE,
  REFRIGERATION_FRESH_MODE,
  REFRIGERATION_ECO_MODE,
  SUPER_MODE_REFRIGERATOR,
  SUPER_MODE_REFRIGERATOR2,
  SUPER_MODE_FREEZER,
  SUPER_MODE_FREEZER2,
  SETPOINT_TEMPERATURE_REFRIGERATOR,
  SETPOINT_TEMPERATURE_REFRIGERATOR2,
  SETPOINT_TEMPERATURE_FREEZER,
  SETPOINT_TEMPERATURE_FREEZER2,
  REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE,
  REFRIGERATION_CHILLER_LEFT_HUMIDITY,
  REFRIGERATION_CHILLER_RIGHT_HUMIDITY,
  SETTING_PRESET,
  WARMCOMPARTEMENT_ACTIVEPRESET,
} from '@/constants/Command'
import type { FlexMode, FridgeFreezerController, FridgeSettingGroup } from '@/controller/FridgeFreezer/definition'
import { actionDebounce, showLoading } from '@/utils/mpHelper'
import { cloneDeep, toNumber } from 'lodash'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack, applianceControlTrack } from '@/dataReport/dataReportUtil'
import { mode } from 'crypto-js'
const props = defineProps<{
  show: boolean
  control: FridgeFreezerController.Control
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
}>()

const modalShow = computed({
  get() {
    return props.show
  },
  set(show) {
    emit('update:show', show)
  },
})

const isVirtualSmartHygieneActive = ref('Appliance.Settings.SmartHygiene.Auto')
const brand = computed(() => (props.control.store.detail?.brand as string).toUpperCase())
const swithchValueTypes = ref(false)

// demo和普通活静氧高亮
const smartHygieneClose = computed(() => {
  if (props.control.store.isVirtualAppliance) {
    if (isVirtualSmartHygieneActive.value == 'Appliance.Settings.SmartHygiene.Close') {
      return true
    } else {
      return false
    }
  } else {
    if (smartHygienMode.value === SMART_HYGIENE_MODE_CLOSE || smartHygieneLiteMode.value === SMART_HYGIENE_MODE_CLOSE) {
      return true
    } else {
      return false
    }
  }
})
const smartHygieneAuto = computed(() => {
  if (props.control.store.isVirtualAppliance) {
    if (isVirtualSmartHygieneActive.value == 'Appliance.Settings.SmartHygiene.Auto') {
      return true
    } else {
      return false
    }
  } else {
    if (smartHygienMode.value === SMART_HYGIENE_MODE_AUTO || smartHygieneLiteMode.value === SMART_HYGIENE_MODE_AUTO) {
      return true
    } else {
      return false
    }
  }
})
const smartHygieneStrongSterilization = computed(() => {
  if (props.control.store.isVirtualAppliance) {
    if (isVirtualSmartHygieneActive.value == 'Appliance.Settings.SmartHygiene.StrongSterilization') {
      return true
    } else {
      return false
    }
  } else {
    if (
      smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
      smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
    ) {
      return true
    } else {
      return false
    }
  }
})
//判断温度设置是否置灰
const isDisabledTemp = (setting: ApplianceSetting) => {
  if (!currentGroup?.value) return
  if (setting.key === FLEX_KEY) return false

  return (
    setting.constraints?.access === 'read' ||
    (isSuperModeFreezerCon.value &&
      [SETPOINT_TEMPERATURE_FREEZER, SETPOINT_TEMPERATURE_FREEZER2].includes(currentGroup?.value.key)) ||
    (isSuperModeRefrigeratorCon.value &&
      [SETPOINT_TEMPERATURE_REFRIGERATOR, SETPOINT_TEMPERATURE_REFRIGERATOR2].includes(currentGroup?.value.key))
  )
}

/**
 * 菜单设置项
 */
const currentGroup = computed(() => props.control.store.currentSettingGroup)

const currentMenuGroupKey = computed(() => props.control.store.currentMenuGroupKey)
let menuSettings = computed(() => getCurrentSettingType(props.control.store.currentMenuSettings))

const localMode = computed(() => props.control.store.localMode)
const isSmartHygieneLite = computed(() => props.control.store.isSmartHygieneLite)
const isNotDisturbMode = computed(() => props.control.store.isNotDisturbMode)

const isSmartHygieneNodisturb = computed(() => props.control.store.isSmartHygieneNodisturb)
const smartHygienMode = computed(() => props.control.store.smartHygieneMode)
const smartHygieneLiteMode = computed(() => props.control.store.smartHygieneLiteMode)

const flexModes = computed(() => props.control.store.flexModes)

const flexDemoMode = ref<FlexMode[]>([])
if (props.control.store.isVirtualAppliance) {
  flexDemoMode.value = [
    {
      BOSCH_name: '冰鲜',
      SIEMENS_name: '微冻',
      bosch_des: '适合作为肉类保鲜空间，无需解冻轻松切片。',
      key: 'Refrigeration.Common.EnumType.FoodPresets.LittleFreezing',
      siemens_des: '适合作为鱼肉类短期存储空间。',
      value: '-4',
    },
    {
      BOSCH_name: '冷藏',
      SIEMENS_name: '冷藏',
      bosch_des: '适合作为普通冷藏空间使用，扩大冷藏空间。',
      key: 'Refrigeration.Common.EnumType.FoodPresets.Cool',
      siemens_des: '适合作为普通冷藏空间使用。',
      value: '4',
    },
    {
      BOSCH_name: '零度',
      SIEMENS_name: '生鲜',
      bosch_des: '适合作为果蔬保鲜的存储空间。',
      key: 'Refrigeration.Common.EnumType.FoodPresets.Fresh',
      siemens_des: '适合作为部分蔬果、奶制品等存储空间。',
      value: '0',
    },
    {
      BOSCH_name: '冷冻',
      SIEMENS_name: '深冻',
      bosch_des: '适合作为普通冷冻空间使用，扩大冷冻空间。',
      key: 'Refrigeration.Common.EnumType.FoodPresets.DeepFreeze',
      siemens_des: '适合作为普通冷冻空间使用。',
      value: '-18',
    },
  ]
}
/**
 * Specialty Zone
 */
const choosePresentMode = actionDebounce({
  call: async (setting) => {
    console.error(setting)
    await setSetting(
      props.control.store._datasource.haId,
      WARMCOMPARTEMENT_ACTIVEPRESET,
      setting.useKey.replace('.Setting', '.SettingList')
    )
    trackEvent(
      'appliance_setting',
      {
        setting_key: WARMCOMPARTEMENT_ACTIVEPRESET,
        setting_value: setting.useKey,
      },
      TrackType.ApplianceDetail,
      setting.key
    )
  },
})

// 速冻
const isSuperModeFreezerCon = computed(() => props.control.store.isSuperModeFreezerCon)
// 速冷
const isSuperModeRefrigeratorCon = computed(() => props.control.store.isSuperModeRefrigeratorCon)
/** 自定义特殊处理的bool值 */
const ModeKeys = [REFRIGERATION_OFF_MODE, REFRIGERATION_VACATION_MODE, REFRIGERATION_ECO_MODE, REFRIGERATION_FRESH_MODE]
const newMenuSettings = ref<ApplianceSetting[]>([])

//冷藏排序
const refrigerateGroupKey = [SETPOINT_TEMPERATURE_REFRIGERATOR, SETPOINT_TEMPERATURE_REFRIGERATOR2]
const sortRefrigerateParams = [
  SUPER_MODE_REFRIGERATOR,
  SUPER_MODE_REFRIGERATOR2,
  SETPOINT_TEMPERATURE_REFRIGERATOR,
  SETPOINT_TEMPERATURE_REFRIGERATOR2,
]
// 冷冻排序
const FreezeGroupKey = [SETPOINT_TEMPERATURE_FREEZER, SETPOINT_TEMPERATURE_FREEZER2]
const sortFreezeParams = [
  SUPER_MODE_FREEZER,
  SUPER_MODE_FREEZER2,
  SETPOINT_TEMPERATURE_FREEZER,
  SETPOINT_TEMPERATURE_FREEZER2,
]
// 百变储鲜室、恒鲜杀菌系统、魔术变温空间排序
const freshStorageGroupKey = [FLEX_KEY, FLEX_MODE_KEY]
const sortFreshStorageParams = [FLEX_KEY, FLEX_MODE_KEY]
// 零度生物保鲜室、零度维他保鲜室排序
const preserveGroupKey = [REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE]
const sortPreserveParams = [
  REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE,
  REFRIGERATION_CHILLER_LEFT_HUMIDITY,
  REFRIGERATION_CHILLER_RIGHT_HUMIDITY,
]
const showGroupUnit = computed(() => {
  if (!currentGroup.value) return false
  return [
    SETPOINT_TEMPERATURE_FREEZER,
    SETPOINT_TEMPERATURE_FREEZER2,
    SETPOINT_TEMPERATURE_REFRIGERATOR,
    SETPOINT_TEMPERATURE_REFRIGERATOR2,
  ].includes(currentGroup?.value.key)
})
const isShowTips = ref(false)
const stopFetch = ref(false)
const flexModeIndex = ref(-100)
if (props.control.store.isVirtualAppliance) {
  flexModeIndex.value = -1
}
watch(
  () => modalShow.value,
  () => {
    if (props.control.store.isVirtualAppliance) {
      if (!menuSettings.value || menuSettings.value.length === 0) return
      newMenuSettings.value = cloneDeep(menuSettings.value)
    }
  }
)
watch(
  () => menuSettings.value,
  (menuSettings) => {
    if (!menuSettings || menuSettings.length === 0) return
    if (!stopFetch.value) newMenuSettings.value = []
    if (props.control.store.isVirtualAppliance) {
      newMenuSettings.value = cloneDeep(menuSettings)
      return
    }
    if (refrigerateGroupKey.includes(currentMenuGroupKey.value)) {
      if (currentGroup.value?.value === '速冷') {
        currentGroup.value.unit = '°C'
      }
      getSortParamsList(sortRefrigerateParams, menuSettings)
    } else if (FreezeGroupKey.includes(currentMenuGroupKey.value)) {
      getSortParamsList(sortFreezeParams, menuSettings)
    } else if (freshStorageGroupKey.includes(currentMenuGroupKey.value)) {
      if (stopFetch.value) return
      flexModeIndex.value = -100
      menuSettings.map((items) => {
        if (items.type == 'Picker' && items.constraints?.access == 'readWrite') {
          flexModeIndex.value = items.value as number
        }
      })
      getSortParamsList(sortFreshStorageParams, menuSettings)

      stopFetch.value = true
    } else if (preserveGroupKey.includes(currentMenuGroupKey.value)) {
      getSortParamsList(sortPreserveParams, menuSettings)
    } else {
      newMenuSettings.value = cloneDeep(menuSettings)
      console.error(newMenuSettings.value, currentGroup.value)
    }

    // stopFetch.value = true
  }
)
function clearFridgeSettingModal() {
  stopFetch.value = false
}
function getSortParamsList(sortParams: string[], menuSettings: ApplianceSetting[]) {
  sortParams.forEach((item) => {
    let curIndex = menuSettings.findIndex((setting) => setting.key === item)
    if (curIndex !== -1 && newMenuSettings.value.length < menuSettings.length) {
      let curSetting = menuSettings.find((setting) => setting.key === item) as ApplianceSetting
      newMenuSettings.value.push(curSetting)
    }
  })
}
function openModal() {
  isShowTips.value = true
}

/**
 * 对groupSetting内每条设置具体分类
 */
function getCurrentSettingType(currentSettingGroup: ApplianceSetting[] | null) {
  if (!currentSettingGroup) return
  currentSettingGroup.forEach((item) => {
    if (item.key === FLEX_MODE_KEY) {
      isFlexSetGrid(item)
    } else if (item.key === SMART_HYGIENE_ENABLED) {
      item.type = 'SmartHygiene'
    } else if (ModeKeys.includes(item.key)) {
      item.type = 'Mode'
    } else if (item.type === 'Double' || item.type === 'Int') {
      isPickerGrid(item)
    } else if (item.type === 'Boolean') {
      isCustomRadio(item)
    } else if (item.type?.includes('Enum')) {
      isEnumGrid(item)
    }
  })
  return currentSettingGroup
}
function isFlexSetGrid(currentSetting: ApplianceSetting) {
  currentSetting.type = 'Flex'
  const index = currentSetting.constraints?.allowedvalues?.findIndex((item) => item === FLEX_MODE_CUSTOM)
  if (index !== -1) {
    const allowedvalue = currentSetting.constraints?.allowedvalues?.splice(index as number, 1)
    const displayvalue = currentSetting.constraints?.displayvalues?.splice(index as number, 1)
    if (currentSetting.constraints) {
      currentSetting.constraints.extrovalue = {
        allowedvalue: allowedvalue ? allowedvalue[0] : '',
        displayvalue: displayvalue ? displayvalue[0] : '',
      }
    }
  }
}
function isCustomRadio(currentSetting: ApplianceSetting) {
  // 指定为 radio 的值
  currentSetting.type = 'Radio'
}
function isEnumGrid(currentSetting: ApplianceSetting) {
  currentSetting.type = 'Enum'
}
function isPickerGrid(currentSetting: ApplianceSetting) {
  // 数字类型  咖啡机COFFEE_BEAN_AMOUNT需要特殊处理
  currentSetting.type = 'Picker'
  const scope = []
  if (
    currentSetting.constraints &&
    currentSetting.constraints.min &&
    currentSetting.constraints.max &&
    currentSetting.constraints.stepsize
  ) {
    for (
      let val = currentSetting.constraints.min;
      val < currentSetting.constraints.max;
      val += currentSetting.constraints.stepsize
    ) {
      scope.push(val)
    }
    currentSetting.scope = scope
  }
}
const temperatureTimer = ref(setTimeout(() => {}))
/**
 * 步进减少
 * @param setting
 */
const decrease = actionDebounce({
  call: async (setting: ApplianceSetting) => {
    if (props.control.store.isVirtualAppliance) {
      if (currentGroup.value?.key === FLEX_KEY) {
        flexModeIndex.value--
      } else {
        ;(setting.value as number)--
      }
      return
    }
    clearTimeout(temperatureTimer.value)
    ;(setting.value as number)--
    flexModeIndex.value = setting.value as number
    temperatureTimer.value = setTimeout(() => {
      applianceControlTrack(
        () => setSetting(props.control.store._datasource.haId, setting.key, setting.value as number),
        'appliance_setting',
        { setting_key: setting.key, setting_value: setting.value },
        'Appliance.Settings.Fridge.Setting'
      )
    }, 1000)
  },
})
/**
 * 步进增加
 * @param setting
 */
const increase = actionDebounce({
  call: async (setting: ApplianceSetting) => {
    if (props.control.store.isVirtualAppliance) {
      if (currentGroup.value?.key === FLEX_KEY) {
        flexModeIndex.value++
      } else {
        ;(setting.value as number)++
      }
      return
    }
    clearTimeout(temperatureTimer.value)
    ;(setting.value as number)++
    flexModeIndex.value = setting.value as number
    temperatureTimer.value = setTimeout(() => {
      applianceControlTrack(
        () => setSetting(props.control.store._datasource.haId, setting.key, setting.value as number),
        'appliance_setting',
        { setting_key: setting.key, setting_value: setting.value },
        'Appliance.Settings.Fridge.Setting1'
      )
    }, 1000)
  },
})
/**
 * bool值修改
 * @param setting
 */
const toggleChange = actionDebounce({
  call: async (setting: ApplianceSetting) => {
    if (props.control.store.isVirtualAppliance) return
    await applianceControlTrack(
      () => setSetting(props.control.store._datasource.haId, setting.key, !setting.value),
      'appliance_setting',
      { setting_key: setting.key, setting_value: !setting.value },
      'Appliance.Settings.Fridge.Setting2'
    )
  },
})
/**
 * option修改
 * @param setting
 * @param index
 */
const optionChange = actionDebounce({
  call: async (setting: ApplianceSetting, index: number) => {
    await setSetting(
      props.control.store._datasource.haId,
      setting.key,
      setting.constraints?.allowedvalues?.[index] as any
    )
  },
})
/**
 * 变温室option修改
 * @param setting
 * @param index1
 */
const flexOptionChange = actionDebounce({
  call: async (key: string, setting: { key: string | number | boolean | object; value: number }) => {
    if (props.control.store.isVirtualAppliance) return (flexModeIndex.value = toNumber(setting.value))
    clearTimeout(temperatureTimer.value)
    // stopFetch.value = false
    await setSetting(props.control.store._datasource.haId, key, setting.key)
      .then((res) => {
        setTimeout(() => {
          toggleChangeFlex()
        }, 500)
      })
      .catch((error) => {})
  },
})

/**
 * 设置新自定义模式到本地
 */
const setNewLocalMode = actionDebounce({
  call: async (temperature?) => {
    stopFetch.value = false
    let res: any = null

    try {
      res = await setSetting(props.control.store._datasource.haId, FLEX_MODE_KEY, FLEX_MODE_CUSTOM)
    } catch (error) {
      res = error
    } finally {
      trackEvent(
        'appliance_setting',
        {
          setting_key: FLEX_MODE_KEY,
          setting_value: FLEX_MODE_CUSTOM,
          successOrNot: res.code == 0,
          error_code: res.code,
          response_msg: res.msg,
        },
        TrackType.ApplianceDetail,
        'Appliance.Settings.Fridge.Setting'
      )
      if (res.code == 0 && temperature) {
        await setSetting(props.control.store._datasource.haId, FLEX_KEY, temperature)
      }
    }
  },
})
/**
 * 开关活氧净
 */
const setSmartHygieneEnabled = actionDebounce({
  delay: 1000,
  call: async (value: boolean, key: string, buttonId: string) => {
    if (props.control.store.isVirtualAppliance) {
      return (isVirtualSmartHygieneActive.value = buttonId)
    }
    if (value) {
      if (
        // 强力模式开
        smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
        smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
      ) {
        await applianceControlTrack(
          () =>
            setCommand(
              props.control.store._datasource.haId,
              smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
                smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
                ? SMART_HYGIENE_CLOSED
                : SMART_HYGIENE_BOOST,
              false
            ),
          'appliance_setting',
          {
            setting_key:
              smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
              smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
                ? SMART_HYGIENE_CLOSED
                : SMART_HYGIENE_BOOST,
            setting_value: false,
          },
          'Appliance.Settings.Fridge.Setting'
        )
      } else if (
        // 活氧净关
        smartHygienMode.value === SMART_HYGIENE_MODE_CLOSE ||
        smartHygieneLiteMode.value === SMART_HYGIENE_MODE_CLOSE
      ) {
        if (!props.control.store.isVirtualAppliance)
          await applianceControlTrack(
            () => setSetting(props.control.store._datasource.haId, SMART_HYGIENE_ENABLED, value),
            'appliance_setting',
            {
              setting_key: SMART_HYGIENE_ENABLED,
              setting_value: value,
            },
            'Appliance.Settings.Fridge.Setting'
          )
      }
    } else {
      // 活氧净开
      if (
        smartHygienMode.value !== SMART_HYGIENE_MODE_CLOSE &&
        smartHygieneLiteMode.value !== SMART_HYGIENE_MODE_CLOSE
      ) {
        if (!props.control.store.isVirtualAppliance)
          await applianceControlTrack(
            () => setSetting(props.control.store._datasource.haId, SMART_HYGIENE_ENABLED, value),
            'appliance_setting',
            {
              setting_key: SMART_HYGIENE_ENABLED,
              setting_value: value,
            },
            'Appliance.Settings.Fridge.Setting'
          )
      }
    }
  },
})
/**
 * 设置强力杀菌
 */
const setSmartHygieneManual = actionDebounce({
  delay: 1000,
  call: async (key: string, buttonId) => {
    if (props.control.store.isVirtualAppliance) return (isVirtualSmartHygieneActive.value = buttonId)
    if (smartHygienMode.value !== SMART_HYGIENE_MODE_CLOSE && smartHygieneLiteMode.value !== SMART_HYGIENE_MODE_CLOSE) {
      // 活氧净开
      await applianceControlTrack(
        () =>
          setCommand(
            props.control.store._datasource.haId,
            smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
              smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
              ? SMART_HYGIENE_CLOSED
              : SMART_HYGIENE_BOOST,
            true
          ),
        'appliance_setting',
        {
          setting_key:
            smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
            smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
              ? SMART_HYGIENE_CLOSED
              : SMART_HYGIENE_BOOST,
          setting_value: true,
        },
        'Appliance.Settings.Fridge.Setting'
      )
    } else {
      // await applianceControlTrack(
      // () =>
      setSetting(props.control.store._datasource.haId, SMART_HYGIENE_ENABLED, true).then((res) => {
        if (res.code === 0) {
          setCommand(
            props.control.store._datasource.haId,
            smartHygienMode.value === SMART_HYGIENE_MODE_MANUAL ||
              smartHygieneLiteMode.value === SMART_HYGIENE_MODE_MANUAL
              ? SMART_HYGIENE_CLOSED
              : SMART_HYGIENE_BOOST,
            true
          )
        }
      })
      // )
    }
  },
})
/**
 * 设置勿扰模式
 */
const setNodisturb = actionDebounce({
  call: async () => {
    if (props.control.store.isVirtualAppliance) return (swithchValueTypes.value = !swithchValueTypes.value)
    {
      applianceControlTrack(
        () =>
          setSetting(props.control.store._datasource.haId, SMART_HYGIENE_NO_DISTURB, !isSmartHygieneNodisturb.value),
        'appliance_setting',
        { setting_key: SMART_HYGIENE_NO_DISTURB, setting_value: !isSmartHygieneNodisturb.value },
        'Appliance.Settings.Fridge.Setting'
      )
    }
  },
})
// demo模式选择高亮
const modeHeightLight = ref<number | undefined>(0)
/**
 * 选择模式
 */
const modeChange = actionDebounce({
  delay: 1000,
  call: async (setting: ApplianceSetting, settingIndex?: number) => {
    if (props.control.store.isVirtualAppliance) {
      uni.hideLoading()
      return (modeHeightLight.value = settingIndex)
    }
    if (setting.key === REFRIGERATION_OFF_MODE) {
      const closeModeKey = newMenuSettings.value.find((items) => items.value === true)
      await applianceControlTrack(
        () => setSetting(props.control.store._datasource.haId, closeModeKey?.key as string, false),
        'appliance_setting',
        { setting_key: closeModeKey?.key as string, setting_value: false },
        'Appliance.Settings.Fridge.Setting.More'
      )
    } else {
      await applianceControlTrack(
        () => setSetting(props.control.store._datasource.haId, setting.key, true),
        'appliance_setting',
        { setting_key: setting.key, setting_value: true },
        'Appliance.Settings.Fridge.Setting'
      )
    }
  },
})
/**
 * 显示弹框
 * @param type
 */
const showTip1 = ref(false)
const showTip2 = ref(false)
const showTip3 = ref(false)
function showNotifyTip(type: string) {
  switch (type) {
    case 'chiller':
      showTip1.value = true
      break
    case 'presetMode':
      showTip2.value = true
      break
    case 'selfSetMode':
      showTip3.value = true
      break
  }
}

/**
 * 预设模式和自定义模式互斥
 */
const toggleChangeFlex = actionDebounce({
  call: async (setting?: ApplianceSetting) => {
    showLoading(async () => {
      // false 预设模式 true自定义模式
      let checked = setting?.value === FLEX_MODE_CUSTOM ? true : false
      if (props.control.store.isVirtualAppliance) {
        return
      }
      if (checked) {
        setNewLocalMode(localMode.value?.temperature) //只保留自定义开关
      } else {
        setNewLocalMode()
      }
    })
  },
})
</script>

<style scoped lang="less">
@import '@/styles/common.less';
@import '@/styles/switch.less';
.setting-box {
  background-color: #f4f4f6;
  padding: 24rpx 24rpx 32rpx 24rpx;
  box-sizing: border-box;
  margin-bottom: 24rpx;
}
.present-box {
  display: flex;
  flex-wrap: wrap;
  background: #f4f4f6;
  padding-bottom: 42rpx;
  .function-title {
    width: 100%;
    padding-left: 24rpx;
    padding-top: 24rpx;
    color: var(--primary-petrol, #2d3746);
    font-size: 14px;
    font-weight: 400;
    opacity: 0.6;
  }
  .present-mode {
    margin-top: 24rpx;
    height: 56rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: var(--primary-petrol, #2d3746);
    font-size: 32rpx;
    font-weight: 400;
  }
}
.widthFull {
  width: 100%;
}
.setting-switch {
  position: relative;
}
.bgGrey {
  background-color: #f4f4f6;
}
/*绿色样式（true的样式）*/
:deep(.wx-switch-input) {
  position: absolute;
  top: 0;
  right: 0;
  .generalSwitch();
}
.setting-name {
  width: 100%;
  display: flex;
  align-items: center;
  .name {
    display: flex;
    align-items: baseline;
  }
  .name-text {
    font-weight: 500;
    font-size: 28rpx;
    color: var(--dark-color);
    opacity: 0.6;
  }
  .question-icon {
    width: 28rpx;
    height: 28rpx;
    padding-left: 6rpx;
  }
}
.pad-top {
  padding-top: 24rpx;
}
.mode-des {
  font-weight: 400;
  font-size: 28rpx;
  line-height: 40rpx;
  color: var(--primary-color);
  padding-bottom: 48rpx;
}
.mode-font {
  font-weight: 600;
  font-size: 32rpx;
  color: var(--dark-color);
  opacity: 0.8;
}
.mode-box {
  flex-wrap: wrap;
}
.mode-con {
  width: 50%;
}
.present-con {
  width: 33%;
}
.setting-in {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: space-between;
  position: relative;
  .bool-name {
    font-size: 32rpx !important;
    opacity: 1 !important;
    padding-bottom: 0 !important;
  }
  .setting-picker {
    width: 100%;
  }
  // picker
  &.jia-jian-box {
    justify-content: space-around !important;
    padding-bottom: 20rpx;
    .num {
      font-weight: 600;
      font-size: 56rpx;
      color: #408df2;
    }
    .mark-icon {
      width: 48rpx;
      height: 48rpx;
    }
  }
  // 枚举
  .flex-grid {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column: 3;
    gap: 28rpx 0;
    .grid-cont {
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      font-size: 32rpx;
      color: var(--dark-color);
      opacity: 0.8;
      .grid-name {
        padding-right: 16rpx;
      }
    }
  }
}
.special-bottom {
  padding-bottom: 24rpx !important;
}
.inactive {
  pointer-events: none;
  opacity: 0.3;
}
.is-setpoint-temperature {
  opacity: 1;
}
.active {
  color: var(--primary-color) !important;
  opacity: 1;
  pointer-events: none;
}
.modal-list {
  font-weight: 400;
  font-size: 32rpx;
  line-height: 48rpx;
  opacity: 0.8;
  color: var(--dark-color);
  text-align: left;
}
// 勿扰模式
.not-disturb-mode {
  .not-disturb-title {
    height: 40rpx;
    display: flex;
    align-items: center;
    .select-img {
      width: 40rpx;
      height: 40rpx;
      padding-right: 20rpx;
    }
    text {
      font-weight: 500;
      font-size: 28rpx;
      color: var(--dark-color);
    }
  }
  .not-disturb-cont {
    font-weight: 400;
    font-size: 24rpx;
    line-height: 34rpx;
    color: var(--dark-color);
    opacity: 0.8;
    padding-left: 60rpx;
    padding-top: 10rpx;
  }
}
.drawer-title-box {
  height: 56rpx;
  .setting-icon {
    width: 28rpx;
    height: 28rpx;
    padding-left: 6rpx;
    padding-top: 18rpx;
  }
  .drawer-title {
    font-weight: 600;
    font-size: 40rpx;
    color: var(--dark-color);
  }
  .grawer-title-unit {
    font-weight: 600;
    font-size: 28rpx;
    color: var(--dark-color);
    float: right;
  }
}
.setting-mode {
  width: 100%;
  height: 132rpx;
  line-height: 132rpx;
  background-color: #f4f4f6;
  box-sizing: border-box;
  float: left;
  text-align: center;
}
.localmode-title {
  padding-right: 10rpx;
}
.setting-unit {
  font-weight: 500;
  font-size: 10px;
  color: var(--dark-color);
  opacity: 0.6;
  padding-left: 6rpx;
}
.bold-font {
  font-weight: 600;
}
.decrease .mark-icon {
  position: absolute;
  top: 36rpx;
  left: 128rpx;
}
.increase .mark-icon {
  position: absolute;
  top: 36rpx;
  right: 128rpx;
}
</style>
